package service

import (
	"bytes"
	"context"
	"core/coreqto"
	"core/corestruct"
	"core/coreutil"
	"core/datetime"
	"core/id"
	mymongo "core/mongo"
	"core/myerrors"
	"fmt"
	"go.mongodb.org/mongo-driver/bson"
	"go.mongodb.org/mongo-driver/bson/primitive"
	"ht/api/htfile/data"
	"ht/api/htfile/mongo"
	htfileserver "ht/server/htfile"
	htfileservice "ht/service/htfile"
	"strconv"
)

type mainService struct {
}

// Save 保存文件
func (p *mainService) Save(m *mongo.File, filedata *[]byte, ctx *corestruct.HttpContext) (*data.FileDto, error) {
	coll := coreutil.MongoUtil.Collection(htfileservice.COLLName)
	ContentType := coreutil.FileUtil.GetFileContentType(filedata)
	m.ContentType = ContentType

	if m.Size/1024/1024 > 12 {
		bucket := coreutil.GetGridfsBucket(htfileservice.COLLName)
		err := bucket.UploadFromStreamWithID(m.Id, m.Name, bytes.NewBuffer(*filedata))
		if err != nil {
			return nil, myerrors.NewByErr(err)
		}
		m.FileId = strconv.FormatInt(m.Id, 10)
	} else {
		m.Data = filedata
		m.FileId = ""

	}
	_, err := coll.InsertOne(context.TODO(), m)
	if err != nil {
		return nil, myerrors.NewByErr(err)
	}
	var r = &data.FileDto{
		Id:          m.Id,
		Name:        m.Name,
		Memo:        m.Memo,
		Url:         htfileservice.GetUrl(m.Id),
		ContentType: m.ContentType,
	}
	htfileserver.PushHtfile(r.Id, r.Name)
	return r, nil

}

// Page 设备分页
func (p *mainService) Page(mm *coreqto.BasePageDtQto, ctx *corestruct.HttpContext) (*corestruct.Page[data.FileInnerDto], error) {
	var filter = make(bson.M)
	if mm.Id > 0 {
		filter["_id"] = mm.Id
	} else {
		if "" != mm.Key {
			filter["name"] = bson.M{"$regex": primitive.Regex{
				Pattern: mm.Key,
				Options: "",
			}}
		}
		if "" != mm.Dtb {
			var dtb, err = mm.GetDtb()
			if err != nil {
				return nil, err
			}
			var dtid = id.GetIdByDate(*dtb)
			filter["_id"] = bson.M{"$gte": dtid}
		}
		if "" != mm.Dte {
			var dte, err = mm.GetDte()
			if err != nil {
				return nil, err
			}
			var dtid = id.GetIdByDate(*dte)
			filter["_id"] = bson.M{"$lt": dtid}
		}

	}

	var pgsvr = &mymongo.PageService[data.FileInnerDto]{
		ColName:  "file",
		Filer:    filter,
		PageNo:   mm.Page,
		PageSize: mm.PageSize,
	}

	r, err := pgsvr.Page()
	if err != nil {
		return nil, err
	}
	for index, v := range r.Records {
		var dt = id.GetDateById(v.Id)
		r.Records[index].CrtDt = datetime.FormatDateTime(dt)
		if v.Size > 1024*1024 {
			r.Records[index].Ssize = fmt.Sprintf("%dM", v.Size/1024/1024)
		} else {
			r.Records[index].Ssize = fmt.Sprintf("%dK", v.Size/1024)
		}

		r.Records[index].Url = htfileservice.GetUrl(v.Id)
	}
	return r, nil
}

var (
	MainService = &mainService{}
)
